#!/python/env/python3.5/bin/python
# coding:utf-8
import time, os, json, re, random
import requests
import zmq
import base64,hashlib

TBID_DIR_PATH = '/tmp/tbid'
IMG_SAVE_PATH = '/tmp'
KEY='PUBGX'
random.seed()

def getPubImg(tbid):
    url = 'http://api.zaizaihui.cn/tool/goods/ext/img2/' + tbid
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        return base64.b64encode(r.content).decode('utf-8')
    return ''

def sign(key,str):
    m = hashlib.md5()
    m.update((key+str).encode(encoding='utf-8'))
    return m.hexdigest()


context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:8000")
while True:
    url = 'http://www.memuu.com/api/v2/miaosha?search=&page=1&count=20&cid=0&from=mobileWeb&c_num=0&hidehb=0&token=null&appid=null';
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        data = r.json()
        sendNum = 10
        sendTbid = ''
        for goods in data['goods']:
            sendTbid = sendTbid + goods['tbid'] + ' '
            sendNum = sendNum - 1
            if sendNum == 0:
                break
        print("获取到的tbid:"+sendTbid+"\n")

        #如果获取的记录和上次发送的记录一样,就不发送了
        try:
            f = open('/tmp/sendlog', 'w+')
            log = f.read()
            if log != sendTbid:
                for goods in data['goods']:
                    tbid = goods['tbid']
                    slogan = goods['slogan']
                    if tbid in log:
                        print(tbid+"上一次已经发送了\n")
                        continue
                    else:
                        img = getPubImg(tbid)
                        if(img == ''):
                            continue
                        msg = json.dumps({'img':img,'slogan':slogan,'title':'一带一路天猫福利35群,天猫福利37群'})
                        signData = sign(KEY, msg)
                        socket.send_string(json.dumps({'key':KEY,'sign':signData,'data':msg}))
                        print(tbid+'---'+slogan+"----发送成功\n")
                        time.sleep(random.randint(30,100))
            f.write(sendTbid)
        finally:
            f.close()

    time.sleep(random.randint(400,700))
